package com.nulldev.util.scripting.ScriptAPI.baseJS.cupJS.parser;

import java.util.List;

import com.nulldev.util.VariableAPI.ArrayUtils;
import com.nulldev.util.VariableAPI.util.strings.splitters.Splitters;
import com.nulldev.util.data.Arrays.arrays.FastLists;
import com.nulldev.util.manage.Macros;
import com.nulldev.util.scripting.ScriptAPI.baseJS.legacy.lexer.BaseJSEnvironment;
import com.nulldev.util.scripting.cup.instruction_sets.sil.insts.LoadNearestRegister;
import com.nulldev.util.scripting.cup.instruction_sets.sil.insts.WriteToRegister;
import com.nulldev.util.scripting.cup.instructions.CupInstruction;

public class CUPDecoder {

	public static void processPayloadSegment(final String str, final BaseJSEnvironment be) {
		final boolean containsFormatting = str.contains("\"") || str.contains("'");
		final List<CupInstruction> INSTRUCTIONS = FastLists.list();
		if (containsFormatting) {
			Macros.unreachable("TODO: FORMATTED SECTIONS");
		} else {
			final String[] instructions = Splitters.splitString(str, " ");
			if (isVariableDecl(instructions)) {
				final String varName = instructions[1];
				final String value = ArrayUtils.last(instructions);
				INSTRUCTIONS.add(new LoadNearestRegister(varName));
				INSTRUCTIONS.add(new WriteToRegister(varName, value));
			} else if (isFunctionDecl(instructions)) {
				Macros.unreachable("TODO: FUNCTIONS");
			} else {
				Macros.unreachable("TODO: UNKNOWN SEGMENT");
			}
		}
		ArrayUtils.printLln(INSTRUCTIONS);
	}

	private static final boolean isFunctionDecl(final String[] instructions) {
		return instructions[0].equals("function");
	}

	private static final boolean isVariableDecl(final String[] instructions) {
		return instructions[0].equals("var") || instructions[0].equals("let") || instructions[0].equals("const");
	}
}
